package sfin.swt.util;

import static org.apache.commons.lang.StringUtils.isBlank;
import static org.apache.commons.lang.StringUtils.isNumeric;

import java.text.DateFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Currency;
import java.util.GregorianCalendar;
import java.util.Locale;

public class FormatterUtil {

	private Locale locale;
	private Currency currency;
	private SimpleDateFormat dateFormatter;
	private NumberFormat numberFormatter;
	
	public FormatterUtil(Locale locale) {
		this.locale = locale;
		this.currency = Currency.getInstance(locale);
		this.dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
		this.numberFormatter = NumberFormat.getInstance(locale);
		this.numberFormatter.setMaximumFractionDigits(2);
	}
	
	public String getCurrencyString(double value){
		String symbol = currency.getSymbol();
		return symbol + " " + numberFormatter.format(value);
	}
	
	public String getStringValue(double value){
		return numberFormatter.format(value);
	}
	
	public String getPercentString(double value){
		return numberFormatter.format(value) + "%";
	}
	
	
	public String getFormattedDate(Calendar calendar){
		if(calendar == null)
			return "";
		return dateFormatter.format(calendar.getTime());
	}
	
	public int parseInt(String value){
		return parseInt(value,-1);
	}
	
	public int parseInt(String value, int whenNull){
		if(isBlank(value) || !isNumeric(value))
			return whenNull;
		return Integer.parseInt(value);
	}
	
	public double parseDouble(String value, double whenNull) throws ParseException{
		if(isBlank(value))
			return whenNull;
		
		return numberFormatter.parse(value).doubleValue();
	}
	
	public String[] getMonthNames(){
		String[] localeMonths = DateFormatSymbols.getInstance( this.locale ).getMonths();
		String[] months = new String[12];
		for(int i = 0; i<months.length; i++){
			months[i] = localeMonths[i];			
		}
		return months;
	}
	
	public Calendar getCalendarInstance(){
		return Calendar.getInstance(locale);
	}

	public Calendar getBefore(int mes, int ano){
		Calendar calendar = new GregorianCalendar(ano,mes,1);
		calendar.add(Calendar.MONTH, -1);
		return calendar;
	}
	
}
